package oop.controller.action.exam;

import java.util.List;

import oop.controller.action.DefaultAction;
import oop.data.Examination;
import oop.db.dao.ExaminationDAO;
import oop.taglib.UtilFunctions;

import org.apache.commons.lang.StringUtils;

public class ListAction extends DefaultAction {

	public static final int PAGE_LENGTH = 30;

	public ListAction() {
	}

	@Override
	public void performImpl() throws Exception {
		title("Danh sách các kì thi");
		String submit = request.getParameter("el_submit");
		if ("delete".equals(submit)) {
			try {
				String[] items = request.getParameterValues("el_exams");
				int count = 0;
				for (String item : items) {
					long id = Long.parseLong(item);
					count += ExaminationDAO.drop(id);
				}
				message("Đã xóa " + count + " mục.");
			} catch (NumberFormatException ex) {
				error("ID không hợp lệ.");
			}
		}

		String pageStr = StringUtils.defaultIfEmpty(request
				.getParameter("page"), "1");
		long page = Integer.parseInt(pageStr);

		List<Examination> exams = ExaminationDAO.fetchByTeacher(getUser()
				.getId(), (page - 1) * PAGE_LENGTH, PAGE_LENGTH);
		long count = ExaminationDAO.countByTeacher(getUser().getId());

		request.setAttribute("exams", exams);
		request.setAttribute("page", page);
		request.setAttribute("pageCount", UtilFunctions.ceil(count / (double)PAGE_LENGTH));
	}

}
